/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 1.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月09日 星期5 11时14分25秒
***************************************************/
// 将队列引入“生产者-消费者”模型中
//       将两个信号量、锁、队列封装为结构体
#include "queue.h"
typedef struct content{
	sem_t semr;
	sem_t semw;
	pthread_mutex_t mutex;
	struct queue *que;
}CON;

void *fun1(void *arg)
{	
	int dat = 0;
	CON *p = (CON *)arg;
	while(1)
	{	
		sem_wait(&p->semw);

		pthread_mutex_lock(&p->mutex);

		dat++;
		push(dat,p->que);

		sem_post(&p->semr);

		pthread_mutex_unlock(&p->mutex);
	}
}

void *fun2(void *arg)
{
	int dat = 0;
	CON *p = (CON *)arg;
	while(1)
	{
		sem_wait(&p->semr);

		pthread_mutex_lock(&p->mutex);

		dat = front(p->que);
		pop(p->que);
		printf("dat = %d\n",dat);
		printf("size = %d\n",size(p->que));

		sem_post(&p->semw);

		pthread_mutex_unlock(&p->mutex);
		sleep(1);
	}
}

int main()
{

	pthread_t tid1 = 0,tid2 = 0;
	int ret = 0;
	CON sem;
	
	sem.que = create_queue();	
	sem_init(&sem.semw,0,10);
	sem_init(&sem.semr,0,0);
	pthread_mutex_init(&sem.mutex,NULL);

	ret = pthread_create(&tid1,NULL,fun1,&sem);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}

	ret = pthread_create(&tid2,NULL,fun2,&sem);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	sem_destroy(&sem.semr);
	sem_destroy(&sem.semw);
	
	pthread_mutex_destroy(&sem.mutex);

	return 0;

}






